package com.wzy.service.reposirory.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.common.base.Youdao.TranslationUtil;
import com.wzy.common.base.result.R;
import com.wzy.common.base.util.ResolveUtil;
import com.wzy.service.reposirory.dto.WordsResponse;
import com.wzy.service.reposirory.entity.*;
import com.wzy.service.reposirory.mapper.UserArticleMapper;
import com.wzy.service.reposirory.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuzhengyu
 * @since 2021-04-05
 */
@Service
public class UserArticleServiceImpl extends ServiceImpl<UserArticleMapper, UserArticle> implements UserArticleService {

    @Autowired
    GlobalWordService globalWordService;
    @Autowired
    UserWordService userWordService;
    @Autowired
    GlobalArticleService globalArticleService;
    @Autowired
    UserArticleMapper userArticleMapper;

    @Autowired
    UserSentenceService userSentenceService;

    @Override
    public R getEveryDayWord(String article, String uid) throws Exception {
        // 判断一下 global article中是否已经存在该文章

        // 如果global article中已经存在该文章就不需要执行存入文章的逻辑了

        // 将文章进行分割
        // 先分解为句级 (utils)
        // 先从全局库中拿一下该文章

        Map<String, Integer> count = new HashMap<String, Integer>(){{
            put("初中",0);
            put("高中",0);
            put("CET4",0);
            put("CET6",0);
            put("考研",0);
        }};


        GlobalArticle globalArticle = globalArticleService.getOne(Wrappers.<GlobalArticle>lambdaQuery().eq(GlobalArticle::getArticle, article));
        // 如果拿不到
        if (globalArticle == null) {
            // 插入一个全局库
            globalArticle = new GlobalArticle();
            Map<String, String> articleMap = TranslationUtil.translateSentence(article);
            String translation = articleMap.get("translation");
            String speakUrl = articleMap.get("speakUrl");
            globalArticle.setArticle(article);
            globalArticle.setTranslate(translation);
            globalArticle.setPronounce(speakUrl);
            globalArticle.setGmtModified(new Date());
            globalArticle.setGmtCreate(new Date());
            globalArticleService.save(globalArticle);
        }

        // 放入到user_article中
        UserArticle userArticle = userArticleMapper.selectOne(Wrappers.<UserArticle>lambdaQuery().eq(UserArticle::getArticle,article).eq(UserArticle::getUid,uid));
        if (userArticle == null) {
            // level next_review_time 没有设置
            userArticle = new UserArticle();
            userArticle.setGmtModified(new Date());
            userArticle.setGmtCreate(new Date());
            userArticle.setUid(Long.valueOf(uid));
            userArticle.setPhases("");
            userArticle.setTranslate(globalArticle.getTranslate());
            userArticle.setAid(globalArticle.getId());
            userArticle.setPronounce(globalArticle.getPronounce());
            userArticle.setArticle(article);
            userArticle.setNextReviewTime(new Date());
            userArticleMapper.insert(userArticle);
        }


        List<String> sentences = ResolveUtil.article2Sentence(article);


        // 对每个句子进行翻译,获得发音\翻译 (sentence)
        UserArticle finalUserArticle1 = userArticle;
        sentences.forEach(sentence -> {
            UserSentence s = userSentenceService.getOne(Wrappers.<UserSentence>lambdaQuery().eq(UserSentence::getSentence,sentence).eq(UserSentence::getUid,uid));
            Map<String, String> sentenceMap = null;
            if(s == null) {
                try {
                    s = new UserSentence();
                    sentenceMap = TranslationUtil.translateSentence(sentence);
                    String sentenceTranslation = sentenceMap.get("translation");
                    String sentenceSpeakUrl = sentenceMap.get("speakUrl");
                    s.setSentence(sentence);
                    s.setTranslate(sentenceTranslation);
                    s.setUid(Long.valueOf(uid));
                    s.setPronounce(sentenceSpeakUrl);
                    s.setUserArticleId(finalUserArticle1.getId());
                    s.setGmtCreate(new Date());
                    s.setGmtModified(new Date());
                    userSentenceService.save(s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            // 分解为单词级
            List<String> words = ResolveUtil.sentence2Word(sentence);
            UserSentence finalS = s;
            words.forEach(word -> {
                try {
                    // 查看该单词是否在全局单词库存储
                    GlobalWord globalWord = globalWordService.getOne(Wrappers.<GlobalWord>lambdaQuery().eq(GlobalWord::getSpell, word));
                    // 如果单词库没有这个单词,就需要查询,并且加入全局单词库
                    if (globalWord == null) {
                        Map<String, String> wordMap = TranslationUtil.translateWord(word);
                        if(wordMap != null) {
                            // 获取释义  explains
                            String explains = wordMap.get("explains");
                            // 获取等级  level
                            String level = wordMap.get("level");
                            // 获取音标
                            String ukPhonetic = wordMap.get("ukPhonetic");
                            String usPhonetic = wordMap.get("usPhonetic");
                            // 获取读音  英音
                            String ukSpeech = wordMap.get("ukSpeech");
                            GlobalWord newWord = new GlobalWord();
                            newWord.setGmtCreate(new Date());
                            newWord.setGmtModified(new Date());
                            newWord.setSpell(word);
                            newWord.setExplains(explains);
                            newWord.setLevel(level);
                            newWord.setUkPhonetic(ukPhonetic);
                            newWord.setUsPhonetic(usPhonetic);
                            newWord.setUkSpeech(ukSpeech);
                            // 保存
                            globalWordService.save(newWord);
                            globalWord = newWord;
                        }

                    }
                    UserWord userWord = userWordService.getOne(Wrappers.<UserWord>lambdaQuery().eq(UserWord::getUid, uid).eq(UserWord::getGwid, globalWord.getId()));
                    if (userWord == null) {
                        userWord = new UserWord();
                        userWord.setUid(Long.valueOf(uid));
                        userWord.setGwid(globalWord.getId());
                        userWord.setSid(finalS.getId().toString());
                        userWord.setStatus("未知");
                        userWord.setGmtModified(new Date());
                        userWord.setGmtCreate(new Date());
                        userWordService.save(userWord);
                    }

                    if (word.equals("harder")) {
                        System.out.println(word);
                    }
                    // 给对应的单词执行+1操作
                    if (globalWord.getLevel() != null && !globalWord.getLevel().equals("") && !globalWord.getLevel().equals(" ")) {
                        count.put(globalWord.getLevel(), count.get(globalWord.getLevel())+1);
                    }

 

                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        });


        int sum = count.get("考研") + count.get("CET6") + count.get("CET4") + count.get("高中") + count.get("初中");
        double kaoyan = (double)count.get("考研") / sum;
        double CET6 = (double)count.get("CET6") / sum;
        double CET4 = (double)count.get("CET4") / sum;
        double heightSchool = (double)count.get("高中") / sum;
        double lowSchool = (double)count.get("初中") / sum;
        String level;
        if (kaoyan > 0.10) {
            level = "考研";
        } else if (CET6 > 0.10) {
            level = "CET6";
        } else if (CET4 > 0.10) {
            level = "CET4";
        } else if (heightSchool > 0.10) {
            level = "高中";
        } else  {
            level = "初中";
        }
        globalArticle.setLevel(level);
        globalArticle.setJuniorHighWordNumber(count.get("初中"));
        globalArticle.setSeniorHighWordNumber(count.get("高中"));
        globalArticle.setCte4WordNumber(count.get("CET4"));
        globalArticle.setCte6WordNumber(count.get("CET6"));
        globalArticle.setPostgraduateWordNumber(count.get("考研"));

        userArticle.setLevel(level);

        userArticleMapper.update(userArticle, Wrappers.<UserArticle>lambdaUpdate().eq(UserArticle::getArticle, article).eq(UserArticle::getUid, uid));
        globalArticleService.updateById(globalArticle);


        List<UserWord> list = userWordService.list(Wrappers.<UserWord>lambdaQuery().eq(UserWord::getUid, uid).eq(UserWord::getStatus, "未知"));
        List<WordsResponse> words = list.stream().map(l -> {
            GlobalWord one = globalWordService.getOne(Wrappers.<GlobalWord>lambdaQuery().eq(GlobalWord::getId, l.getGwid()));
            return new WordsResponse(l,one);
        }).collect(Collectors.toList());

        List<UserSentence> sentenceList = userSentenceService.list(Wrappers.<UserSentence>lambdaQuery().eq(UserSentence::getUid,uid).eq(UserSentence::getUserArticleId, userArticle.getId()));

        return R.ok().data("words", words).data("article", userArticle).data("sentences", sentenceList);
    }

    @Override
    public R createUserArticle(String uid, String level) throws Exception {
        GlobalArticle one = globalArticleService.getOne(Wrappers.<GlobalArticle>lambdaQuery().eq(GlobalArticle::getLevel, level).last(" ORDER BY RAND() limit 1"));
        return getEveryDayWord(one.getArticle(), uid);

    }
}
